package com.wish.exception;

import com.wish.util.SpringUtils;
import org.springframework.context.MessageSource;

import java.util.Locale;


/**
 * spring的事务处理默认只针对runtimeException做事务回滚
 * @author lf
 */
@SuppressWarnings("serial")
public class BaseException extends RuntimeException {
	protected Object[] args;

	public void setArgs(Object[] args) {
		this.args = args;
	}

	public BaseException(String msg) {
		super(translateMessage(msg, null));
	}

	public BaseException(String msg, Object[] args) {
		super(translateMessage(msg, args));
		this.args = args;
	}

	public BaseException(String msg, Throwable cause) {
		super(translateMessage(msg, null), cause);
	}

	private static String translateMessage(String msg, Object[] args) {
    	if (msg != null && msg.length() > 0 && msg.charAt(0) == '{'
    			&& msg.charAt(msg.length()-1) == '}') {
    		return SpringUtils.getBean(MessageSource.class).getMessage(msg.substring(1, msg.length()-1), args, Locale.getDefault());
    	}
    	return msg;
	}
}
